/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.mzk.oai.metadataRepository.repository.records.impl;

import cz.mzk.kramerius.commons.Dom4jUtils;
import cz.mzk.oai.metadataRepository.metadata.MetadataFormat;
import cz.mzk.oai.metadataRepository.repository.Identifier;
import cz.mzk.oai.metadataRepository.repository.collections.MetadataCollection;
import cz.mzk.oai.metadataRepository.repository.records.Record;
import cz.mzk.oai.metadataRepository.repository.records.presentAndDeleted.PresentRecordsManager;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.dom4j.Document;

/**
 *
 * @author Martin Řehánek (rehan at mzk.cz)
 */
public class FilePresentRecordsManager extends AbstractFileRecordsManager implements PresentRecordsManager {

    private static final Logger logger = Logger.getLogger(FilePresentRecordsManager.class.getName());
    private static final String METADATA_DIR_SUFFIX = "_present";

    public FilePresentRecordsManager(MetadataCollection collection) {
        super(collection);
    }

    public FilePresentRecord getRecord(Identifier identifier, MetadataFormat format) {
        File metadataDir = getMetadataDir(format);
        return new FilePresentRecord(identifier, format, metadataDir, collection);
    }

//    public List<Record> getRecords(MetadataFormat format) {
//        List<Identifier> idList = getIdentifiers(format);
//        return createRecords(idList, format);
//    }
    List<Record> createRecords(List<Identifier> idList, MetadataFormat format) {
        List<Record> result = new ArrayList<Record>(idList.size());
        for (Identifier id : idList) {
            FilePresentRecord record = getRecord(id, format);
            result.add(record);
        }
        return result;
    }

    String getMetadataDirSuffix() {
        return METADATA_DIR_SUFFIX;
    }

    public void updateRecord(Identifier identifier, MetadataFormat format, Document metadata) throws IOException {
        FilePresentRecord record = getRecord(identifier, format);
        persistRecord(record, metadata);
    }

    private void persistRecord(FilePresentRecord record, Document metadata) throws IOException {
        File recordFile = record.getMetadataFile();
        boolean persisted = Dom4jUtils.saveDocument(metadata, recordFile, Dom4jUtils.PrintType.ORIGINAL);
        if (!persisted) {
            logger.log(Level.SEVERE, "Failed to persist {0}", record.getMetadataFile().getAbsolutePath());
        }
    }
}
